package com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.repository;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.StringUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.common.ResponseResult;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.*;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowEntrustRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.UserRepository;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.entities.*;
import com.iwhalecloud.citybrain.flow.platform.manager.infrastructure.mapper.FlowEntrustDAO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.regex.Pattern;

/**
 * @author Huhangfei
 * @date 2021-11-17 09:09
 */
@Service
@Slf4j
public class FlowEntrustRepositoryImpl implements FlowEntrustRepository {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private FlowEntrustDAO flowEntrustDAO;

   @Override
    public ResponseResult insertOrUpdate(FlowEntrustVo flowEntrustVo){

        if(flowEntrustVo==null){
            log.info("参数不能全部为空");
            return ResponseResult.fail(100,"参数不能全部为空");
        }
        if(flowEntrustVo.getId()==0){
            return insertFlowEntrust(flowEntrustVo);
        }
        else{
            return updateFlowEntrust(flowEntrustVo);
        }

    }
    @Override
    public ResponseResult insertFlowEntrust(FlowEntrustVo flowEntrustVo) {
        FlowEntrustQueryVo flowEntrustQueryVo=new FlowEntrustQueryVo();
        User user = userRepository.getCurrentUser();
        if(flowEntrustVo.getStatus()==1){
            flowEntrustQueryVo.setStatus(1);
            flowEntrustQueryVo.setIsDelete(0);
            flowEntrustQueryVo.setClient(user.getUserCode());
            List<FlowEntrustVo> list=selectFlowEntrust(flowEntrustQueryVo);
            if(list!=null && list.size()>0) {
                return ResponseResult.fail(100,"已经存在正在启用的默认代理，不能新建默认代理");
            }
        }
        if(flowEntrustVo==null){
            return ResponseResult.fail(100,"参数不能全部为空");
        }
        FlowEntrustQueryVo flowEntrustQueryVo1=new FlowEntrustQueryVo();
        flowEntrustQueryVo1.setCode(flowEntrustVo.getCode());
        flowEntrustQueryVo1.setIsDelete(0);
        List<FlowEntrustVo> list1=selectFlowEntrust(flowEntrustQueryVo1);
        if(list1!=null && list1.size()>0){
            return ResponseResult.fail(100,"该流程编码已经被使用，请重新输入流程编码");
        }
        int flag=flowEntrustVo.getId();
        log.info("flag:{}",flag);
        flowEntrustVo.setClient(user.getUserCode());
        flowEntrustVo.setClientDepartment(user.getOrgCode());
        Date date=new Date();
        flowEntrustVo.setCreateTime(date);
        flowEntrustVo.setUpdateTime(date);
        FlowEntrust flowEntrust=new FlowEntrust();
        BeanUtils.copyProperties(flowEntrustVo,flowEntrust);
        flowEntrust.setTrustee(flowEntrustVo.getTrusteeCode());
        flowEntrust.setTrusteeDepartment(flowEntrustVo.getTrusteeDepartmentCode());
        flowEntrust.setIsDefault(1);
        if(flowEntrustDAO.insertEntrust(flowEntrust)==1){
            log.info("默认委托创建成功");
            List<FlowEntrustDetail> flowEntrustDetails=convert(flowEntrustVo.getFlowEntrustDetailVoList(),flowEntrust.getId());
            if(flowEntrustDetails!=null && flowEntrustDetails.size()!=0){
                int k=flowEntrustDAO.insertEntrustDetailBatch(flowEntrustDetails);
                if(k>0){
                    log.info("自定义委托创建成功");
                    return ResponseResult.success("默认委托和自定义委托创建成功");
                }
                else{
                    log.info("自定义委托创建失败");
                    return ResponseResult.success("默认委托创建成功，自定义委托创建失败");
                }
            }
            else{
                return ResponseResult.success("默认委托创建成功");
            }
        }
        return ResponseResult.fail(100,"默认委托创建失败");
    }

    @Override
    public ResponseResult updateFlowEntrust(FlowEntrustVo flowEntrustVo) {
        if(flowEntrustVo==null){
            return ResponseResult.fail(100,"输入的参数不能全部为空");
        }
        Date date=new Date();
        flowEntrustVo.setUpdateTime(date);
        FlowEntrust flowEntrust=new FlowEntrust();
        BeanUtils.copyProperties(flowEntrustVo,flowEntrust);
        flowEntrust.setTrustee(flowEntrustVo.getTrusteeCode());
        flowEntrust.setTrusteeDepartment(flowEntrustVo.getTrusteeDepartmentCode());
        if(flowEntrust.getStatus()!=0 && flowEntrust.getStatus()!=-1){
            FlowEntrustQueryVo flowEntrustQueryVo=new FlowEntrustQueryVo();
            flowEntrustQueryVo.setStatus(1);
            flowEntrustQueryVo.setIsDelete(0);
            flowEntrustQueryVo.setClient(flowEntrustDAO.selectEntrustClientById(flowEntrustVo.getId()));
            List<FlowEntrustVo> test=selectFlowEntrust(flowEntrustQueryVo);
            if(test!=null && test.size()>0) {
                FlowEntrustVo flowEntrustVo1=test.get(0);
                if(flowEntrustVo1.getId()!=flowEntrustVo.getId()) {
                    return ResponseResult.fail(100, "已经存在正在启用的默认代理，不能启动当前默认代理");
                }
            }
        }
        flowEntrust.setIsDefault(1);
        int flag=flowEntrustDAO.updateEntrust(flowEntrust);
        if(flag==1){
            List<FlowEntrustDetailVo> list=flowEntrustVo.getFlowEntrustDetailVoList();
            updateFlowEntrustDetail(list,flowEntrustVo.getId());
            return ResponseResult.success("更新成功");
        }
        return ResponseResult.fail(100,"更新失败");
    }

    public boolean updateFlowEntrustDetail(List<FlowEntrustDetailVo> flowEntrustDetailVos,int entrustId){

        if(flowEntrustDetailVos==null || flowEntrustDetailVos.size()==0 ){
            return false;
        }
        flowEntrustDetailVos.forEach(item->{
            Date date=new Date();
            FlowEntrustDetail flowEntrustDetail=new FlowEntrustDetail();
            BeanUtils.copyProperties(item,flowEntrustDetail);
            flowEntrustDetail.setUpdateTime(date);
            flowEntrustDetail.setTrustee(item.getTrusteeCode());
            flowEntrustDetail.setTrusteeDepartment(item.getTrusteeDepartmentCode());
            if(item.getId()==0){
                flowEntrustDetail.setClient(flowEntrustDAO.selectEntrustClientById(entrustId));
                flowEntrustDetail.setClientDepartment(flowEntrustDAO.selectEntrustClientDepartmentById(entrustId));
                flowEntrustDetail.setEntrustId(entrustId);
                flowEntrustDetail.setCreateTime(date);
                flowEntrustDetail.setUpdateTime(date);
                int id=flowEntrustDAO.insertEntrustDetail(flowEntrustDetail);
                if(id>0){
                    log.info("自定义委托{}插入成功",id);
                    return;
                }
                else{
                    log.info("自定义委托{}插入失败",id);
                }
            }
            else{
                int flag=flowEntrustDAO.updateEntrustDetail(flowEntrustDetail);
                if(flag>0){
                    log.info("自定义委托{}更新成功",item.getId());
                    return;
                }
            }
        });
        return true;
    }

    @Override
    public List<FlowEntrustVo> selectFlowEntrust(FlowEntrustQueryVo flowEntrustQueryVo) {
        FlowEntrustQuery flowEntrustQuery=new FlowEntrustQuery();
        BeanUtils.copyProperties(flowEntrustQueryVo,flowEntrustQuery);

        flowEntrustQuery.setClient(flowEntrustQueryVo.getClient());
        flowEntrustQuery.setIsDelete(0);
        List<FlowEntrust> temp=flowEntrustDAO.selectByClient(flowEntrustQuery);
        List<FlowEntrustVo> result=new ArrayList<>();
        temp.forEach(it->{
            FlowEntrustVo flowEntrustVo=new FlowEntrustVo();
            BeanUtils.copyProperties(it,flowEntrustVo);
            flowEntrustVo.setClientCode(it.getClient());
            flowEntrustVo.setClient(transferCodeToName(it.getClient()));
            flowEntrustVo.setTrustee(transferCodeToName(it.getTrustee()));
            flowEntrustVo.setTrusteeCode(it.getTrustee());
            result.add(flowEntrustVo);
        });
        log.info("result:{}",result);
        return result;
    }

    public List<FlowEntrustDetailVo> selectFlowEntrustDetail(FlowEntrustDetailQuery flowEntrustDetailQuery){
        List<FlowEntrustDetail> list=flowEntrustDAO.selectEntrustDetail(flowEntrustDetailQuery);
        List<FlowEntrustDetailVo> result=new ArrayList<>();
        list.forEach(item->{
            String name=transferCodeToName(item.getTrustee());
            FlowEntrustDetailVo flowEntrustDetailVo=new FlowEntrustDetailVo();
            BeanUtils.copyProperties(item,flowEntrustDetailVo);
            flowEntrustDetailVo.setTrustee(name);
            flowEntrustDetailVo.setTrusteeCode(item.getTrustee());
            flowEntrustDetailVo.setTrusteeDepartmentCode(item.getTrusteeDepartment());
            flowEntrustDetailVo.setTrusteeDepartment(transferOrgCodeToName(item.getTrusteeDepartment()));
            flowEntrustDetailVo.setClient(transferCodeToName(item.getClient()));
            flowEntrustDetailVo.setClientCode(item.getClient());
            flowEntrustDetailVo.setClientDepartmentCode(item.getClientDepartment());
            flowEntrustDetailVo.setClientDepartment(transferCodeToName(item.getClientDepartment()));
            result.add(flowEntrustDetailVo);
        });
        return result;
    }

    public List<FlowEntrustVo>  selectFormEntrustAndDetail(FlowEntrustQueryVo flowEntrustQueryVo){
        User user = userRepository.getCurrentUser();
        FlowEntrustQuery flowEntrustQuery=new FlowEntrustQuery();
        FlowEntrustDetailQuery flowEntrustDetailQuery=new FlowEntrustDetailQuery();
        BeanUtils.copyProperties(flowEntrustQueryVo,flowEntrustQuery);
        flowEntrustQuery.setClient(user.getUserCode());
        flowEntrustDetailQuery.setClient(user.getUserCode());
        flowEntrustQuery.setIsDelete(0);
        if(user!=null && user.getUserType().equals("SUPER")){
            flowEntrustQuery.setClient(null);
            flowEntrustDetailQuery.setClient(null);
        }
        List<FlowEntrustVo> result=new ArrayList<>();
        List<FlowEntrust> temp=flowEntrustDAO.selectByClient(flowEntrustQuery);
        temp.forEach(item->{
            FlowEntrustVo flowEntrustVo1=new FlowEntrustVo();
            BeanUtils.copyProperties(item,flowEntrustVo1);
            flowEntrustVo1.setClientCode(item.getClient());
            flowEntrustVo1.setClient(transferCodeToName(item.getClient()));
            flowEntrustVo1.setTrusteeCode(item.getTrustee());
            flowEntrustVo1.setTrusteeDepartmentCode(item.getTrusteeDepartment());
            flowEntrustVo1.setTrustee(transferCodeToName(item.getTrustee()));
            result.add(flowEntrustVo1);
        });
        BeanUtils.copyProperties(flowEntrustQueryVo,flowEntrustDetailQuery);
        flowEntrustDetailQuery.setIsDelete(0);
        List<FlowEntrust> list=flowEntrustDAO.selectEntrustAndDetail(flowEntrustDetailQuery);
        list.forEach(item->{
            FlowEntrustVo flowEntrustVo1=new FlowEntrustVo();
            BeanUtils.copyProperties(item,flowEntrustVo1);
            flowEntrustVo1.setClientCode(item.getClient());
            flowEntrustVo1.setClient(transferCodeToName(item.getClient()));
            flowEntrustVo1.setTrustee(transferCodeToName(item.getTrustee()));
            flowEntrustVo1.setTrusteeCode(item.getTrustee());
            flowEntrustVo1.setTrusteeDepartmentCode(item.getTrusteeDepartment());
            result.add(flowEntrustVo1);
        });

        return getPageableResult(result,flowEntrustQueryVo.getPageNumber(),flowEntrustQueryVo.getPageSize());
    }

    @Override
    public FlowEntrustVo selectByClientAndModelKey(FlowEntrustQueryForComputeVo flowEntrustQueryForComputeVo){
       if(flowEntrustQueryForComputeVo==null){
           return null;
       }
       if(StringUtils.isBlank(flowEntrustQueryForComputeVo.getClient())){
           return null;
       }
       FlowEntrustQuery flowEntrustQuery=new FlowEntrustQuery();
       flowEntrustQuery.setClient(flowEntrustQueryForComputeVo.getClient());
       flowEntrustQuery.setIsDelete(0);
       flowEntrustQuery.setStatus(1);
       List<FlowEntrustVo> result=new ArrayList<>();
       List<FlowEntrust> temp=flowEntrustDAO.selectByClient(flowEntrustQuery);
       temp.forEach(item->{
           FlowEntrustVo flowEntrustVo1=new FlowEntrustVo();
           BeanUtils.copyProperties(item,flowEntrustVo1);
           result.add(flowEntrustVo1);
       });
       FlowEntrustVo  flowEntrustVo;
       if(result!=null && result.size()>0){
           flowEntrustVo=result.get(0);
       }else{
           return null;
       }
       if(StringUtils.isBlank(flowEntrustQueryForComputeVo.getModelKey())){
           return flowEntrustVo;
       }
       FlowEntrustDetailQuery flowEntrustDetailQuery=new FlowEntrustDetailQuery();
       flowEntrustDetailQuery.setModelKey(flowEntrustQueryForComputeVo.getModelKey());
       flowEntrustDetailQuery.setClient(flowEntrustQueryForComputeVo.getClient());
       flowEntrustDetailQuery.setStatus(1);
       flowEntrustDetailQuery.setEntrustId(flowEntrustVo.getId());
       List<FlowEntrustDetail> list=flowEntrustDAO.selectEntrustDetail(flowEntrustDetailQuery);
       List<FlowEntrustDetailVo> list1=new ArrayList<>();
       list.forEach(item->{
           FlowEntrustDetailVo flowEntrustDetailVo=new FlowEntrustDetailVo();
           BeanUtils.copyProperties(item,flowEntrustDetailVo);
           list1.add(flowEntrustDetailVo);
       });
        flowEntrustVo.setFlowEntrustDetailVoList(list1);
       return flowEntrustVo;

    }
    @Override
    public ResponseResult deleteFlowEntrustData(FlowEntrustVo flowEntrustVo) {
        if(flowEntrustVo==null){
            return ResponseResult.fail(100,"参数不能为空");
        }
        FlowEntrust flowEntrust=new FlowEntrust();
        BeanUtils.copyProperties(flowEntrustVo,flowEntrust);
        int flag=flowEntrustDAO.deleteEntrustData(flowEntrust);
        if(flag==1){
            log.info("默认委托删除成功");
            List<Integer> ids=flowEntrustDAO.queryEntrustDetail(flowEntrust.getId());
            int k=flowEntrustDAO.deleteEntrustDetail(ids);
            if(k>0){
                log.info("自定义委托删除成功");
                return ResponseResult.success("默认委托删除成功，自定义委托删除成功");
            }else{
                log.info("自定义委托删除失败");
                return ResponseResult.success("默认委托删除成功，自定义委托删除失败");
            }
        }
        return ResponseResult.fail(100,"默认委托删除失败");
    }


    public List<FlowEntrustDetail> convert(List<FlowEntrustDetailVo> list, int entrustId){
        List<FlowEntrustDetail> flowEntrustDetails=new ArrayList<>();
        Date date=new Date();
        User user = userRepository.getCurrentUser();
        list.forEach(item->{
            FlowEntrustDetail flowEntrustDetail=new FlowEntrustDetail();
            if(item!=null){
                BeanUtils.copyProperties(item,flowEntrustDetail);
                flowEntrustDetail.setClient(user.getUserCode());
                flowEntrustDetail.setClientDepartment(user.getOrgCode());
                flowEntrustDetail.setCreateTime(date);
                flowEntrustDetail.setUpdateTime(date);
                flowEntrustDetail.setEntrustId(entrustId);
                flowEntrustDetail.setTrustee(item.getTrusteeCode());
                flowEntrustDetail.setTrusteeDepartment(item.getTrusteeDepartmentCode());
                flowEntrustDetails.add(flowEntrustDetail);
            }
        });
        return flowEntrustDetails;
    }

    @Override
    public ResponseResult updateStatus(FlowEntrustUpdateVo flowEntrustUpdateVo){
       if(flowEntrustUpdateVo==null){
           return ResponseResult.fail(100,"参数不能为空");
       }
        Date date=new Date();
       if(flowEntrustUpdateVo.getIsDefault()==1){
           if(flowEntrustUpdateVo.getStatus()==1){
               FlowEntrustQueryVo flowEntrustQueryVo=new FlowEntrustQueryVo();
               flowEntrustQueryVo.setStatus(1);
               flowEntrustQueryVo.setIsDelete(0);
               //User user = userRepository.getCurrentUser();
               String clientCode=flowEntrustDAO.selectEntrustClientById(flowEntrustUpdateVo.getId());
               flowEntrustQueryVo.setClient(clientCode);
               List<FlowEntrustVo> list=selectFlowEntrust(flowEntrustQueryVo);
               if(list!=null && list.size()>0) {
                   return ResponseResult.fail(100,"已经存在正在启用的默认代理，不能开启当前默认代理");
               }
           }
           int flag=flowEntrustDAO.updateDefaultStatus(flowEntrustUpdateVo.getId(),flowEntrustUpdateVo.getStatus(),date);
           if(flowEntrustUpdateVo.getStatus()==0){
               flowEntrustDAO.updateStatusByEntrustId(flowEntrustUpdateVo.getId(),flowEntrustUpdateVo.getStatus(),date);
           }
           if(flag>0){
               return ResponseResult.success("更新成功");
           }
           else{
               return ResponseResult.fail(100,"更新失败");
           }

       }
       if(flowEntrustUpdateVo.getIsDefault()==0){
           if(flowEntrustUpdateVo.getStatus()==1){
               int status=flowEntrustDAO.queryEntrustStatusByDetailId(flowEntrustUpdateVo.getId());
               if(status==0){
                   return ResponseResult.fail(100,"默认委托的状态没有开启，自定义委托的不能生效");
               }
           }

           int flag=flowEntrustDAO.updateStatusById(flowEntrustUpdateVo.getId(),flowEntrustUpdateVo.getStatus(),date);
           if(flag>0){
               return ResponseResult.success("更新成功");
           }
           else{
               return ResponseResult.fail(100,"更新失败");
           }
       }
       return null;
    }
    @Override
    public ResponseResult deleteEntrustOrDetail(FlowEntrustUpdateVo flowEntrustUpdateVo){
       if(flowEntrustUpdateVo==null){
            return ResponseResult.fail(100,"参数不能为空");
        }
       if(flowEntrustUpdateVo.getIsDefault()==1){
           return deleteFlowEntrust(flowEntrustUpdateVo.getId());
       }
       if(flowEntrustUpdateVo.getIsDefault()==0){
           List<Integer> ids=new ArrayList<>();
           ids.add(flowEntrustUpdateVo.getId());
           int k = flowEntrustDAO.deleteEntrustDetail(ids);
           if (k > 0) {
               return ResponseResult.success("自定义委托删除成功");
           } else {
               return ResponseResult.fail(100,"自定义委托删除失败");
           }
       }
       return null;
    }

    public ResponseResult deleteFlowEntrust(int id) {
        Date date=new Date();
        int flag=flowEntrustDAO.deleteEntrust(id,date);
        if(flag==1){
            log.info("默认委托删除成功");
            List<Integer> ids=flowEntrustDAO.queryEntrustDetail(id);
            if(ids!=null && ids.size()>0) {
                int k = flowEntrustDAO.deleteEntrustDetail(ids);
                if (k > 0) {
                    log.info("自定义委托删除成功");
                    return ResponseResult.success("默认委托和自定义委托删除成功");
                } else {
                    log.info("自定义委托删除失败");
                    return ResponseResult.success("默认委托删除成功，自定义委托删除失败");
                }
            }
            return ResponseResult.success("默认委托删除成功");
        }
        return ResponseResult.fail(100,"默认委托删除失败");
    }

    @Override
    public boolean deleteFlowEntrustDetailData(List<Integer> ids) {
        if(ids==null || ids.size()==0){
            return false;
        }
        int k=flowEntrustDAO.deleteEntrustDetail(ids);
        if(k>0){
            log.info("自定义委托删除成功");
            return true;
        }else{
            log.info("自定义委托删除失败");
        }
        return false;
    }

    /**
     * 把编码转换为名字（从用户中心）
     * @param code
     * @return
     */
    public String transferCodeToName(String code){
       if(StringUtils.isBlank(code)){
           return null;
       }
        Pattern pattern=Pattern.compile("^[-\\+]?[\\d]*$");
       if(pattern.matcher(code).matches()){
           User user=userRepository.getUserWithOrgByCodeFromUserCenter(code);
           if(user!=null){
               return user.getUserName();
           }
       }
       return code;
    }

    /**
     * 把组织编码转换为组织名称（从用户中心）
     * @param orgCode
     * @return 组织名称
     */
    @Override
    public String transferOrgCodeToName(String orgCode){
        String orgName="";
        if(StringUtils.isBlank(orgCode)){
            return null;
        }
        Pattern pattern=Pattern.compile("^[-\\+]?[\\d]*$");
        if(pattern.matcher(orgCode).matches()){
            orgName=userRepository.getOrgNameByCode(orgCode);
            return orgName;
        }
        return orgCode;
    }

    /**
     * 条件查询 测试
     * @param flowEntrustQueryVo
     * @return
     */
    @Override
    public List<FlowEntrustVo> selectEntrustByCondition2(FlowEntrustQueryVo flowEntrustQueryVo){
        User user=userRepository.getCurrentUser();
        if("SUPER".equals(user.getUserType())){
            flowEntrustQueryVo.setClient(null);
        }
        else{
            flowEntrustQueryVo.setClient(user.getUserCode());
        }
        if(StringUtils.isNotBlank(flowEntrustQueryVo.getTrustee())){
           List<String> trustees=queryUserByName(flowEntrustQueryVo.getTrustee());
            if(CollectionUtils.isEmpty(trustees)){
                return null;
            }
            else{
                flowEntrustQueryVo.setTrustees(trustees);
            }
        }
        FlowEntrustDetailQuery flowEntrustDetailQuery=new FlowEntrustDetailQuery();
        flowEntrustDetailQuery.setClient(flowEntrustQueryVo.getClient());
        flowEntrustDetailQuery.setStatus(flowEntrustQueryVo.getStatus());
        flowEntrustDetailQuery.setTrustees(flowEntrustQueryVo.getTrustees());
        flowEntrustDetailQuery.setFlowName(flowEntrustQueryVo.getFlowName());
        List<FlowEntrustDetail> flowEntrustDetails=flowEntrustDAO.selectEntrustDetailByCondition(flowEntrustDetailQuery);
        List<Integer> ids=new ArrayList<>();
        Map<Integer,List<FlowEntrustDetail>> map=new HashMap<>();
        for(int i=0;i<flowEntrustDetails.size();i++){
            FlowEntrustDetail item=flowEntrustDetails.get(i);
            int id=item.getEntrustId();
            if(!ids.contains(id)){
                ids.add(id);
            }
            List<FlowEntrustDetail> temp=new ArrayList<>();
            if(map.containsKey(id)){
                temp=map.get(id);
            }
            temp.add(item);
            map.put(id,temp);
        }
        FlowEntrustQuery flowEntrustQuery=new FlowEntrustQuery();
        flowEntrustQuery.setClient(flowEntrustQueryVo.getClient());
        flowEntrustQuery.setStatus(flowEntrustQueryVo.getStatus());
        flowEntrustQuery.setIsDelete(0);
        flowEntrustQuery.setEntrustName(flowEntrustQueryVo.getEntrustName());
        flowEntrustQuery.setTrustees(flowEntrustQueryVo.getTrustees());
        List<FlowEntrust> list=flowEntrustDAO.selectEntrustByCondition(flowEntrustQuery);
        List<Integer> ids2=new ArrayList<>();
        for(int i=0;i<list.size();i++){
            FlowEntrust item=list.get(i);
            int id=item.getId();
            if(!ids2.contains(id)){
                ids2.add(id);
            }
        }
        if(StringUtils.isNotBlank(flowEntrustQueryVo.getFlowName())){   //流程名称不为空 求交集
            ids.retainAll(ids2);
        }
        else{
            if(StringUtils.isNotBlank(flowEntrustQueryVo.getEntrustName())){  //流程名称为空 委托名称不为空
                ids=ids2;
            }
            else{                        //流程名称为空 委托名称为空 受托人不为空 求并集
                for(int i=0;i<ids2.size();i++){
                    if(!ids.contains(ids2.get(i))){
                        ids.add(ids2.get(i));
                    }
                }
            }
        }
        List<FlowEntrustVo> result=new ArrayList<>();
        if(!CollectionUtils.isEmpty(ids)){
            FlowEntrustQuery flowEntrustQuery1=new FlowEntrustQuery();
            flowEntrustQuery1.setIds(ids);
            flowEntrustQuery1.setStatus(flowEntrustQueryVo.getStatus());
            flowEntrustQuery1.setIsDelete(0);
            List<FlowEntrust> entrustList=flowEntrustDAO.selectEntrustByCondition(flowEntrustQuery1);
            for(int i=0;i<entrustList.size();i++){
                FlowEntrustVo flowEntrustVo=convertEntrustToVo(entrustList.get(i));
                if(map.containsKey(flowEntrustVo.getId())){
                    List<FlowEntrustDetail> temp=map.get(flowEntrustVo.getId());
                    List<FlowEntrustDetailVo> flowEntrustDetailVo=convertEntrustDetailToVo(temp,flowEntrustVo.getEntrustName(),flowEntrustVo.getCode());
                    flowEntrustVo.setFlowEntrustDetailVoList(flowEntrustDetailVo);
                }
                result.add(flowEntrustVo);
            }
        }
        return getPageableResult(result,flowEntrustQueryVo.getPageNumber(),flowEntrustQueryVo.getPageSize());
    }

    //条件查询默认委托 新版
    @Override
    public List<FlowEntrustVo> selectEntrustByCondition(FlowEntrustQueryVo flowEntrustQueryVo){
        User user=userRepository.getCurrentUser();
        if("SUPER".equals(user.getUserType())){
            flowEntrustQueryVo.setClient(null);
        }
        else{
            flowEntrustQueryVo.setClient(user.getUserCode());
        }
        if(StringUtils.isNotBlank(flowEntrustQueryVo.getTrustee())){
            List<String> trustees=queryUserByName(flowEntrustQueryVo.getTrustee());
            if(CollectionUtils.isEmpty(trustees)){
                return null;
            }
            else{
                flowEntrustQueryVo.setTrustees(trustees);
            }
        }
        FlowEntrustQuery flowEntrustQuery=new FlowEntrustQuery();
        BeanUtils.copyProperties(flowEntrustQueryVo,flowEntrustQuery);
        flowEntrustQuery.setIsDelete(0);
        List<FlowEntrust> list=flowEntrustDAO.selectEntrustByCondition(flowEntrustQuery);
        List<FlowEntrustVo> result=new ArrayList<>();
        list.forEach(item->{
            FlowEntrustVo flowEntrustVo=convertEntrustToVo(item);
            FlowEntrustDetailQuery flowEntrustDetailQuery=new FlowEntrustDetailQuery();
            flowEntrustDetailQuery.setEntrustId(item.getId());
            flowEntrustDetailQuery.setStatus(flowEntrustQueryVo.getStatus());
            flowEntrustDetailQuery.setTrustees(flowEntrustQueryVo.getTrustees());
            flowEntrustDetailQuery.setFlowName(flowEntrustQueryVo.getFlowName());
            flowEntrustVo.setFlowEntrustDetailVoList(convertEntrustDetailToVo(flowEntrustDAO.selectEntrustDetailByCondition(flowEntrustDetailQuery),item.getEntrustName(),item.getCode()));
            result.add(flowEntrustVo);
        });
        return getPageableResult(result,flowEntrustQueryVo.getPageNumber(),flowEntrustQueryVo.getPageSize());
    }

    public List<String> queryUserByName(String name){
        if(StringUtils.isBlank(name)){
            return null;
        }
        List<User> user=userRepository.getUserByNameFromUserCenter(name);
        List<String> userIds=new ArrayList<>();
        if(!CollectionUtils.isEmpty(user)){
            user.forEach(item->{
                userIds.add(item.getUserId());
            });
        }
        return userIds;
    }
    //条件查询时把默认委托转换为Vo
    public FlowEntrustVo convertEntrustToVo(FlowEntrust flowEntrust){
        FlowEntrustVo flowEntrustVo=new FlowEntrustVo();
        BeanUtils.copyProperties(flowEntrust,flowEntrustVo);
        flowEntrustVo.setClientCode(flowEntrust.getClient());
        flowEntrustVo.setClient(transferCodeToName(flowEntrust.getClient()));
        flowEntrustVo.setClientDepartmentCode(flowEntrust.getClientDepartment());
        flowEntrustVo.setClientDepartment(transferOrgCodeToName(flowEntrust.getClientDepartment()));
        flowEntrustVo.setTrusteeCode(flowEntrust.getTrustee());
        flowEntrustVo.setTrustee(transferCodeToName(flowEntrust.getTrustee()));
        flowEntrustVo.setTrusteeDepartmentCode(flowEntrust.getTrusteeDepartment());
        flowEntrustVo.setTrusteeDepartment(transferOrgCodeToName(flowEntrust.getTrusteeDepartment()));
        return flowEntrustVo;
    }
    //条件查询时把自定义委托转换为Vo
    public List<FlowEntrustDetailVo> convertEntrustDetailToVo(List<FlowEntrustDetail> flowEntrustDetails,String entrustName,String code){
        List<FlowEntrustDetailVo> result=new ArrayList<>();
        flowEntrustDetails.forEach(item->{
            FlowEntrustDetailVo flowEntrustDetailVo=new FlowEntrustDetailVo();
            BeanUtils.copyProperties(item,flowEntrustDetailVo);
            flowEntrustDetailVo.setClientCode(item.getClient());
            flowEntrustDetailVo.setClient(transferCodeToName(flowEntrustDetailVo.getClient()));
            flowEntrustDetailVo.setClientDepartmentCode(flowEntrustDetailVo.getClientDepartment());
            flowEntrustDetailVo.setClientDepartment(transferOrgCodeToName(flowEntrustDetailVo.getClientDepartment()));
            flowEntrustDetailVo.setTrusteeCode(flowEntrustDetailVo.getTrustee());
            flowEntrustDetailVo.setTrustee(transferCodeToName(flowEntrustDetailVo.getTrustee()));
            flowEntrustDetailVo.setTrusteeDepartmentCode(flowEntrustDetailVo.getTrusteeDepartment());
            flowEntrustDetailVo.setTrusteeDepartment(transferOrgCodeToName(flowEntrustDetailVo.getTrusteeDepartment()));
            flowEntrustDetailVo.setEntrustName(entrustName);
            flowEntrustDetailVo.setCode(code);
            flowEntrustDetailVo.setIsDefault(0);
            result.add(flowEntrustDetailVo);
        });
        return result;
    }
    //为查询添加分页
    private List<FlowEntrustVo> getPageableResult(List<FlowEntrustVo> flowEntrustVo,int pageNum,int pageSize) {
        PageInfo<FlowEntrustVo> pageInfo = new PageInfo<>(flowEntrustVo);
        int end=flowEntrustVo.size();
        List<FlowEntrustVo> list=new ArrayList<>();
        if(pageNum==0) pageNum=1;
        if(pageSize==0) pageSize=10;
        if(end>pageSize*pageNum){
            end=pageSize*pageNum;
        }
        list=flowEntrustVo.subList(pageSize*(pageNum-1),end);
        Page<FlowEntrustVo> result = null;
        try {
            result = new Page<>();
            result.setPageNum(pageNum).setPageSize(pageSize).addAll(list);
            result.setTotal(pageInfo.getTotal());
            return result;
        } finally {
            if (Objects.nonNull(result)) {
                result.close();
            }
        }
    }
    @Override
    public FlowEntrustVo selectEntrustById(FlowEntrustQueryVo flowEntrustQueryVo){
        int id=flowEntrustQueryVo.getId();
        if(id==0){
            return null;
        }
        List<FlowEntrust> flowEntrusts=flowEntrustDAO.selectEntrustById(id);
        if(CollectionUtils.isEmpty(flowEntrusts)){
            return null;
        }
        FlowEntrustVo flowEntrustVo=convertEntrustToVo(flowEntrusts.get(0));
        FlowEntrustDetailQuery flowEntrustDetailQuery=new FlowEntrustDetailQuery();
        flowEntrustDetailQuery.setEntrustId(flowEntrustVo.getId());
        flowEntrustVo.setFlowEntrustDetailVoList(selectFlowEntrustDetail(flowEntrustDetailQuery));
        return flowEntrustVo;
    }

}
